<template>
  <div style="padding-bottom: 80px">
    <a-spin :spinning="loading">
      <!-- 学生选择 -->
      <a-card :bordered="false" :bodyStyle="{ padding: '16px' }">
        <div>
          <a-button type="primary" style="margin-right: 10px" @click="$refs.creatStudent.showDraw()">创建新学员</a-button>
          <a-button style="margin-right: 10px" @click="$refs.student.showModel()">选择在校学员</a-button>
        </div>
        <div class="studentInfo" v-if="studentInfo">
          <span class="infoBySelf">
            <span class="tags">
              <a-tag color="green" v-if="studentInfo.type == 1">在读</a-tag>
              <a-tag color="blue" v-if="studentInfo.type == 3">潜在</a-tag>
              <a-tag v-if="studentInfo.type == 2">历史</a-tag>
            </span>
            <span class="name">{{ studentInfo.name }}</span>
            <span class="phone">
              {{ studentInfo.main_phone }}
              <span v-if="studentInfo.main_parent_type && studentInfo.main_parent_type > 0">({{
                studentInfo.main_parent_type == 1
                  ? '本人'
                  : studentInfo.main_parent_type == 2
                    ? '妈妈'
                    : studentInfo.main_parent_type == 3
                      ? '爸爸'
                      : studentInfo.main_parent_type == 4
                        ? '爷爷'
                        : studentInfo.main_parent_type == 5
                          ? '奶奶'
                          : studentInfo.main_parent_type == 6
                            ? '外公'
                            : studentInfo.main_parent_type == 7
                              ? '外婆'
                              : ''
              }})</span>
            </span>
            <span class="edit">
              <a @click="$refs.editStudent.showDraw(studentInfo.id)">
                <a-icon type="edit"></a-icon>
              </a>
            </span>
          </span>
        </div>
      </a-card>
      <!-- 购买项目表格 -->
      <a-card :bordered="false" style="margin-top: 10px" :bodyStyle="{ padding: '16px' }" v-if="studentInfo">
        <div class="buyThingsInfo">
          <div>
            选择校区：
            <a-select style="width: 150px" v-model="form.structures_id" :disabled="status" placeholder="请先选择校区">
              <a-select-option v-for="(item, index) in schoolSelect" :key="index" :value="item.id">{{
                item.name
                }}</a-select-option>
            </a-select>
            <span v-if="form.structures_id">
              <a-button type="primary" style="margin: 0 20px 20px 20px"
                @click="showChild('courseComponents')">选择课程</a-button>
              <a-button type="primary" style="margin: 0 20px 20px 0"
                @click="showChild('itemComponents')">选择物品</a-button>
              <a-button type="primary" style="margin: 0 20px 20px 0" @click="showChild('cost')">选择费用</a-button>
            </span>
          </div>
          <a-table v-if="data.length > 0" :columns="columns" :dataSource="data" :pagination="false"
            :scroll="{ x: 1200, y: 500 }" style="border: 1px solid #e8e8e8; margin-top: 10px">
            <div slot="name" slot-scope="text, record, index">
              <span style="
                  display: inline-block;
                  width: 150px;
                  white-space: nowrap;
                  overflow: hidden;
                  text-overflow: ellipsis;
                  line-height: 12px;
                ">{{ record.name }}</span>

              <a-select size="small" v-model="record.course_type" class="courseTypeSelectApply"
                v-if="record.project_type == 1" style="width: 60px; font-size: 10px"
                @change="changeCourseType(record, index)">
                <a-select-option :value="0">购买</a-select-option>
                <a-select-option :value="1">新报</a-select-option>
                <a-select-option :value="2">续报</a-select-option>
                <a-select-option :value="3">扩科</a-select-option>
              </a-select>
              <p style="margin-top: 10px" v-if="record.project_type == 1 && record.course_type_num == 2">
                选择班级：
                <a-select v-model="record.class_id" style="width: 200px" placeholder="请选择班级"
                  @change="changeCourseType(record, index)" allowClear>
                  <a-select-option v-for="(item, index) in record.class" :key="index" :value="item.id">
                    <a-tooltip placement="topLeft">
                      <template slot="title">{{ item.name }} </template>
                      {{ item.name }}
                    </a-tooltip>
                  </a-select-option>
                </a-select>
              </p>
              <div v-if="courseCalidity && record.project_type == 1 && record.choice_combo.type == 1">
                <span>课程有效期：</span>
                <a-date-picker @change="changeCourse($event, record)" :allowClear="false" />
              </div>
            </div>
            <!-- 定价标准 -->
            <span slot="price_rule" slot-scope="text, record, index">
              <span v-if="record.project_type == 1">
                <a-select v-model="record.price_type" style="width: 200px" v-if="record.price.length > 0"
                  @change="changePriceType(record, index, record.buy_number)">
                  <a-select-opt-group label="按课时收费">
                    <a-select-option v-for="(item, index) in record.price" :key="index" :value="item.id"
                      v-if="item.type == 1">{{
                        item.name }}</a-select-option>
                  </a-select-opt-group>
                  <a-select-opt-group label="按天收费">
                    <a-select-option v-for="(item, index) in record.price" :key="index" :value="item.id"
                      v-if="item.type == 2">{{
                        item.name }}</a-select-option>
                  </a-select-opt-group>
                </a-select>
              </span>
              <span v-else-if="record.project_type == 2">￥{{ record.unit_price }}/件</span>
              <span v-else-if="record.project_type == 3">￥{{ record.unit_price }}/笔</span>
            </span>
            <!-- 购买数量 -->
            <span slot="buyNumber" slot-scope="text, record, index">
              <a-input-number :min="1" :step="1" v-model="record.buy_number"
                @change="changeTotalNum(record, index, record.disable)" :disabled="record.disable" />
            </span>
            <!-- 赠送数量 -->
            <span slot="give_num" slot-scope="text, record, index">
              <!-- @change="changeTotalNum(record, index, record.disable)" -->
              <span v-if="record.project_type == 1">
                <a-input-number :min="0" v-model="record.give_number" />
              </span>
              <span v-else>-</span>
            </span>
            <!-- 优惠折扣 -->
            <span slot="disCount" slot-scope="text, record, index">
              <a-input :style="{ width: 'calc(100%)' }" v-model="record.discount.value"
                @change="changeDiscount(record, index, record.disable)"
                onkeyup="this.value=this.value.replace(/[^\d.]/g,'')">
                <a-select slot="addonBefore" v-model="record.discount.type" style="width: 80px" :defaultValue="1"
                  @change="changeDiscount(record, index, record.disable)">
                  <a-select-option :value="1">直减</a-select-option>
                  <a-select-option :value="2">折扣</a-select-option>
                </a-select>
              </a-input>
            </span>
            <!-- 签约数量 -->
            <span slot="total_number" slot-scope="text, record, index">
              <span v-if="record.project_type == 1">
                <span v-if="record.choice_combo.type == 2">
                  <span style="display: inline-block; width: 300px; text-align: left; padding-left: 16px">
                    开始日期：
                    <a-date-picker :allowClear="false" v-model="record.buy_start_time" placeholder="不选择默认为当日"
                      @change="changeDate(record, index)" />
                  </span>
                  <br />
                  <span
                    style="display: inline-block; width: 300px; text-align: left; padding-left: 16px; margin-top: 10px">结束日期：&nbsp;&nbsp;&nbsp;{{
                      record.buy_end_time || '--' }} (共{{
                      record.buy_number + record.give_number
                    }}天)</span>
                </span>
                <span v-else>
                  <span>{{ record.buy_number + record.give_number || '0' }}课时</span>
                </span>
              </span>
              <!-- record.total_number -->
              <span v-else-if="record.project_type == 2">￥{{ record.buy_number + record.give_number || '0' }}/件</span>
              <span v-else-if="record.project_type == 3">￥{{ record.buy_number + record.give_number || '0' }}/笔</span>
            </span>
            <span slot="signing_price" slot-scope="text, record, index">
              {{ Number(record.signing_price).toFixed(2) }}
            </span>

            <span slot="action" slot-scope="text, record, index">
              <a @click="delProject(record, index)">删除</a>
            </span>
          </a-table>
          <div class="receivable" v-if="+Number(form.receivable) >= 0 && data.length > 0">
            应收金额：
            <span class="receivable_num">￥{{ +Number(form.receivable) }}</span>
          </div>
        </div>
        <course-model ref="course" :able="1" @receive="courseData"></course-model>
        <item-model ref="item" :able="1" @receive="itemData"></item-model>
        <cost-model ref="cost" :able="1" @receive="costData"></cost-model>
      </a-card>
      <!-- 支付信息 -->
      <a-card :bordered="false" style="margin-top: 10px" :bodyStyle="{ padding: '16px' }"
        v-if="+Number(form.receivable) >= 0 && data.length > 0">
        <div class="otherInfo">
          <div class="title">支付信息</div>
          <div class="form_">
            <a-form-model :model="form" :label-col="labelCol" :wrapper-col="wrapperCol">
              <a-form-model-item label="应收金额">￥{{ +Number(form.receivable) }}</a-form-model-item>
              <a-form-model-item label="付款方式">
                <div class="payWays">
                  <div v-for="(item, index) in btnStyle" :key="index" class="payWayBtn">
                    <a-checkbox @change="changePayWay($event, item.type, index)" style="width: 128px">
                      <a-icon :type="item.icon" :style="{ color: item.color, 'margin-right': '10px' }"></a-icon>
                      {{ item.text }}
                    </a-checkbox>
                    <span v-if="item.check" style="text-align: right">
                      <a-input style="outline: none; border: none; width: 80px; box-shadow: none; text-align: right"
                        onkeyup="this.value=this.value.replace(/[^\d.]/g,'');" v-model="item.price"></a-input>元
                    </span>
                  </div>
                </div>
              </a-form-model-item>
              <a-form-model-item label="实收金额" v-if="form.real_price">
                <span style="color: #ff8534; font-size: 24px">￥{{ +Number(form.real_price) }}</span>
              </a-form-model-item>
              <a-form-model-item label="欠费金额" v-if="Number(form.receivable) - Number(form.real_price) > 0">
                <span style="color: #ff8534; font-size: 24px">￥{{ (Number(form.receivable) -
                  Number(form.real_price)).toFixed(2) }}</span>
              </a-form-model-item>
            </a-form-model>
          </div>
        </div>
      </a-card>
      <!-- 其他信息 -->
      <a-card :bordered="false" style="margin-top: 10px" :bodyStyle="{ padding: '16px' }">
        <div class="otherInfo">
          <div class="title">其他信息</div>
          <div class="form_">
            <a-form-model :model="form" :label-col="labelCol" :wrapper-col="wrapperCol">
              <a-form-model-item label="经办日期">
                <a-date-picker v-model="form.purchase_at" :allowClear="false" />
              </a-form-model-item>
              <a-form-model-item label="业绩归属人">
                <a-select style="width: 200px" placeholder="请选择业绩归属人" mode="multiple" v-model="form.user_id">
                  <a-select-option v-for="(item, index) in teacherSelect" :key="index" :value="item.user_school_id">{{
                    item.name
                    }}</a-select-option>
                </a-select>
              </a-form-model-item>
              <!--        -->
              <a-form-model-item label="经办人">
                <a-input placeholder="请填写经办人" style="width: 200px" v-model="form.operator" />
              </a-form-model-item>
              <a-form-model-item label="备注">
                <a-textarea placeholder="最多输入100字" :autoSize="{ minRows: 4, maxRows: 10 }" allowClear :maxLength="100"
                  style="width: 400px" v-model="form.order_remarks" />
              </a-form-model-item>
            </a-form-model>
          </div>
        </div>
      </a-card>
      <a-card class="footer" :bodyStyle="{ padding: '6px 16px 12px', marginTop: '10px', height: '100%' }">
        共{{ data.length }}个项目
        <!-- @click条件： 要有学员和购买项目信息 -->
        <a-button type="primary" style="margin-right: 20px" @click="sureApply()">确认报名</a-button>
      </a-card>
      <student-model ref="student" :studentArr="readingStudent_index" @reload="studentModelReturnData"></student-model>
      <create-student ref="creatStudent" @reload="reloadStudent"></create-student>
      <edit-student ref="editStudent" @return="reloadStudent"></edit-student>
      <!-- 确认报名弹窗 -->
      <a-modal title="确认报名" :visible="sureApplyVisible" @cancel="sureApplyVisible = false" @ok="submit()"
        :confirm-loading="sureconfirmLoading" :width="1080">
        <a-alert message="请仔细核对信息，避免信息填写错误。确定报名后，学员即可安排上课。" banner />

        <div class="studentInfo" style="border: none" v-if="studentInfo">
          <span class="infoBySelf">
            <span class="name" style="font-size: 16px; color: #333" v-if="studentInfo">{{ studentInfo.name }}</span>
            <span class="phone">
              {{ studentInfo.main_phone }}
              <span v-if="studentInfo.main_parent_type && studentInfo.main_parent_type > 0">({{
                studentInfo.main_parent_type == 1
                  ? '本人'
                  : studentInfo.main_parent_type == 2
                    ? '妈妈'
                    : studentInfo.main_parent_type == 3
                      ? '爸爸'
                      : studentInfo.main_parent_type == 4
                        ? '爷爷'
                        : studentInfo.main_parent_type == 5
                          ? '奶奶'
                          : studentInfo.main_parent_type == 6
                            ? '外公'
                            : studentInfo.main_parent_type == 7
                              ? '外婆'
                              : ''
              }})</span>
            </span>
          </span>
        </div>
        <a-table :columns="sureApplyColumns" :dataSource="data" :pagination="false" :scroll="{ x: 'max-content' }"
          class="user_management_table" style="border: 1px solid #e8e8e8; margin-top: 15px">
          <!-- 购买数量 -->
          <!-- <span slot="buyNumber" slot-scope="text,record,index">{{text||'-'}}</span> -->
          <span slot="buyNumber" slot-scope="text">{{ text || '-' }}</span>
          <!-- 赠送数量 -->
          <span slot="give_num" slot-scope="text, record">{{ record.give_number || '-' }}</span>
          <span slot="class_name" slot-scope="text, record">
            <span v-if="record.class && record.class_id">
              <span v-for="(item, index) in record.class" :key="index">
                <span v-if="record.class_id == item.id">{{ item.name }}</span>
              </span>
            </span>
            <span v-else>-</span>
          </span>
        </a-table>
        <div class="receivable" v-if="+Number(form.receivable) >= 0">
          应收金额：
          <span class="receivable_num">￥{{ +Number(form.receivable) }}</span>
        </div>
        <div class="applyInfomation">
          <div>
            <span>收款方式：</span>
            <span v-for="(item, index) in btnStyle" :key="index">
              <span v-if="item.check && +Number(item.price) >= 0" style="margin-right: 10px">
                <a-icon :type="item.icon" :style="{ color: item.color }"></a-icon>
                {{ item.text }}
              </span>
            </span>
          </div>
          <div v-if="+Number(form.real_price) >= 0">
            <span>实收金额：</span>
            <span>
              <span style="color: #ff8534; font-size: 24px">￥{{ +Number(form.real_price) }}</span>
            </span>
          </div>
          <div v-if="Number(form.receivable) - Number(form.real_price) > 0">
            <span>欠费金额：</span>
            <span style="color: #ff8534; font-size: 24px">￥{{ (Number(form.receivable) -
              Number(form.real_price)).toFixed(2)
              }}</span>
          </div>

          <div>
            <span>付款日期：</span>
            <span>{{ moment(form.purchase_at).format('YYYY-MM-DD') }}</span>
          </div>
        </div>
      </a-modal>
      <!-- 冲突 -->
      <a-modal title="学员冲突" :visible="studentVisible" @ok="studentOk" @cancel="studentVisible = false" okText="忽略冲突"
        okType="danger" :zIndex="1100">
        <div class="title">
          <div class="title-left">
            <a-icon type="warning" style="margin-right: 8px; color: #fdaba9" theme="filled" />排课冲突提示
          </div>
        </div>
        <div class="datas">
          <div style="color: #f14133">
            <a-icon type="warning" style="margin-right: 8px" theme="filled" />
            学员冲突({{ conflict.length }})
          </div>
          <div v-for="(item, index) in conflict" :key="index"
            style="padding-left: 10px; margin-top: 10px; margin-bottom: 24px">
            <div>
              <span v-for="(val, i) in item.class.student" :key="i">
                {{ val.name }}
                <span v-if="i < item.class.student.length - 1">，</span>
              </span>
            </div>
            <div>{{ item.class.name }}</div>
            <div>
              {{ item.start_time | dayc | weeks }}
              <span style="color: #999">{{ item.class_start_time }} ~ {{ item.class_end_time }}</span>
            </div>
          </div>
        </div>
      </a-modal>
    </a-spin>
  </div>
</template>

<script>
import studentModel from '@/components/singleStudent'
import createStudent from '@/components/studentDrawer/addStudent'
import editStudent from '@/components/studentDrawer/editStudent'
import { accountList } from '@/api/account'
import courseModel from '@/components/course'
import { newCoursesList } from '@/api/courseCharge'
import itemModel from '@/components/item'
import costModel from '@/components/cost'
import { campusList } from '@/api/structure'
import moment from 'moment'
import { signUp, ruleStudent, studentInfo } from '@/api/student'
import { checkStudent } from '@/api/class'
import { getCourseInfo } from '@/api/config'
export default {
  components: {
    costModel,
    itemModel,
    courseModel,
    createStudent,
    editStudent,
    studentModel,
  },
  data() {
    return {
      //冲突
      studentVisible: false,
      sureconfirmLoading: false,
      conflict: [],
      loading: false,
      status: false, //判断校区是否可以更换
      labelCol: { span: 3 },
      wrapperCol: { span: 14 },
      schoolSelect: [], //选择校区的下拉数据
      teacherSelect: [], //业绩归属人下拉
      readingStudent_index: [], //被选择的学员在`选择在读学员`中的回显
      courseSelectRows: [], //被选择的课程在`选择课程`中的回显
      studentInfo: null, //学员信息
      sureApplyVisible: false,
      form: {
        structures_id: undefined, //选择校区
        purchase_at: moment(),
        user_id: undefined, //跟进人==业绩归属人  多选
        operator: this.$store.state.user.info.name || undefined, //经办人==用户信息
        order_remarks: undefined, //订单备注
        receivable: null,
        real_price: null,
      },
      //付款方式
      btnStyle: [
        {
          type: 1,
          text: '支付宝',
          color: '#1890ff',
          icon: 'alipay-circle',
          check: false,
          price: 0,
        },
        {
          type: 2,
          text: '微信',
          color: '#52c42a',
          icon: 'wechat',
          check: false,
          price: 0,
        },
        {
          type: 3,
          text: '现金',
          color: '#FF7F24',
          icon: 'transaction',
          theme: 'filled',
          check: false,
          price: 0,
        },
        {
          type: 4,
          text: '网银转账',
          color: '#1296db',
          icon: 'global',
          check: false,
          price: 0,
        },
        {
          type: 5,
          text: 'POS机刷卡',
          color: '#39d63e',
          icon: 'credit-card',
          check: false,
          price: 0,
        },
      ],
      //表格头
      columns: [
        {
          title: '购买项目',
          dataIndex: 'name',
          width: 350,
          align: 'left',
          fixed: 'left',
          scopedSlots: { customRender: 'name' }
        },
        {
          title: '定价标准',
          dataIndex: 'price',
          width: 220,
          scopedSlots: { customRender: 'price_rule' }
        },
        {
          title: '购买数量',
          dataIndex: 'buy_number',
          width: 150,
          scopedSlots: { customRender: 'buyNumber' },
        },
        {
          title: '赠送数量',
          dataIndex: 'give_num',
          ellipsis: true,
          width: 150,
          scopedSlots: { customRender: 'give_num' },
        },
        {
          title: '优惠/折扣',
          dataIndex: 'disCount',
          ellipsis: true,
          width: 150,
          scopedSlots: { customRender: 'disCount' },
        },
        {
          title: '签约数量/签约时长',
          dataIndex: 'total_number',
          align: 'center',
          width: 150,
          scopedSlots: { customRender: 'total_number' },
        },
        {
          title: '签约金额',
          dataIndex: 'signing_price',
          align: 'center',
          width: 100,
          scopedSlots: { customRender: 'signing_price' },
        },
        {
          title: '操作',
          dataIndex: 'action',
          width: 80,
          align: 'center',
          fixed: 'right',
          scopedSlots: { customRender: 'action' },
        },
      ],
      // 表格数据
      data: [],
      //确认报名弹窗 表格
      sureApplyColumns: [
        {
          title: '购买项目',
          dataIndex: 'name',
          width: 300,
          align: 'left',
          scopedSlots: { customRender: 'name' },
        },
        {
          title: '购买数量',
          dataIndex: 'buy_number',
          scopedSlots: { customRender: 'buyNumber' },
        },
        {
          title: '赠送数量',
          dataIndex: 'give_num',
          ellipsis: true,
          scopedSlots: { customRender: 'give_num' },
        },
        {
          title: '班级',
          dataIndex: 'class_name',
          ellipsis: true,
          scopedSlots: { customRender: 'class_name' },
        },
        {
          title: '签约金额',
          dataIndex: 'signing_price',
          ellipsis: true,
          customRender(text) {
            return `${'￥' + text}` || '-'
          },
        },
      ],
      //课程有效期
      courseCalidity: false,
    }
  },
  created() {
    accountList({ school_id: this.$store.state.user.school, pageSize: 999999999 })
      .then((res) => {
        this.teacherSelect = res.data
      })
      .catch((err) => {
        this.$message.error(err.data.message || '获取业绩归属人列表失败')
      })
    campusList({ school_id: this.$store.state.user.school })
      .then((res) => {
        this.schoolSelect = res
      })
      .catch((err) => {
        this.$message.error(err.data.message || '获取校区列表失败')
      })
    this.loading = true
    if (this.$route.query.info) {
      if (this.$route.query.structure_id) {
        this.form.structures_id = Number(this.$route.query.structure_id)
        if (this.$route.query.courseID) {
          newCoursesList({
            structures_id: this.form.structures_id,
            school_id: this.$store.state.user.school,
          }).then((res) => {
            res.data.forEach((val) => {
              if (val.id == Number(this.$route.query.courseID)) {
                this.courseData([val])
              }
            })
          })
        }
      }
    }
    if (this.$route.query.id) {
      studentInfo(this.$route.query.id)
        .then((res) => {
          this.reloadStudent(res)
          if (this.$route.query.structure_id) {
            this.form.structures_id = Number(this.$route.query.structure_id)
            if (this.$route.query.courseID) {
              newCoursesList({
                structures_id: this.form.structures_id,
                school_id: this.$store.state.user.school,
              }).then((res) => {
                res.data.forEach((val) => {
                  if (val.id == Number(this.$route.query.courseID)) {
                    this.courseData([val])
                  }
                })
              })
            }
          }
        })
        .catch((err) => {
          this.$message.error('获取学员信息失败，请刷新重试')
        })
    }
    let that = this
    setTimeout(function () {
      that.loading = false
    }, 1000)
    this.getCourseSet()
  },
  methods: {
    //课程有效期
    changeCourse(date, data) {
      console.log(date, data)
      let hour_due_time = moment(date).format('YYYY-MM-DD')
      data.hour_due_time = hour_due_time
      console.log(this.data)
    },
    //获取课程配置
    getCourseSet() {
      getCourseInfo({
        school_id: this.$store.state.user.school,
        key: 'course_setting',
      })
        .then((res) => {
          if (res.value && JSON.stringify(res.value) != '{}') {
            this.courseCalidity = res.value.valid_time
          } else {
          }
        })
        .catch((err) => {
          // this.loading = false
          this.$message.error(err.data.message || '加载失败')
        })
    },
    studentOk() {
      this.sureconfirmLoading = true
      let params = JSON.parse(JSON.stringify(this.form))
      params.school_id = this.$store.state.user.school
      // params.name = this.studentInfo.name
      params.receivable = params.receivable || '0'
      params.student_id = this.studentInfo.id
      params.purchase_at = moment(params.purchase_at).format('YYYY-MM-DD')
      let btnStyle = JSON.parse(JSON.stringify(this.btnStyle))
      params.real_price_arr = []
      btnStyle.forEach((val) => {
        if (val.check && val.price && Number(val.price) > 0) {
          params.real_price_arr.push({
            charge_type: val.type,
            real_price: val.price,
          })
        }
      })

      params.content_arr = JSON.parse(JSON.stringify(this.data))
      params.content_arr.forEach((val) => {
        if (val.buy_start_time) {
          val.buy_start_time = moment(val.buy_start_time).format('YYYY-MM-DD')
        }
        if (isNaN(Number(val.give_number)) || !val.give_number) {
          val.give_number = 0
        }
      })
      if (params.content_arr.length > 0) {
        params.content_arr.forEach((val) => {
          val.discount = JSON.stringify(val.discount)
        })
      }
      signUp(params)
        .then((res) => {
          this.sureconfirmLoading = false
          this.$message.success('报名/续费成功')
          this.$router.push({ name: 'receipt', query: { id: res.id, type: res.id } })
        })
        .catch((err) => {
          this.sureconfirmLoading = false
          this.$message.error(err.data.message || '报名/续费失败')
        })
    },
    submit() {
      let params = JSON.parse(JSON.stringify(this.form))
      params.school_id = this.$store.state.user.school
      // params.name = this.studentInfo.name
      params.receivable = params.receivable || '0'
      params.student_id = this.studentInfo.id
      params.purchase_at = moment(params.purchase_at).format('YYYY-MM-DD')
      let btnStyle = JSON.parse(JSON.stringify(this.btnStyle))
      params.real_price_arr = []
      btnStyle.forEach((val) => {
        if (val.check && val.price && Number(val.price) > 0) {
          params.real_price_arr.push({
            charge_type: val.type,
            real_price: val.price,
          })
        }
      })
      params.content_arr = JSON.parse(JSON.stringify(this.data))
      params.content_arr.forEach((val) => {
        if (val.buy_start_time) {
          val.buy_start_time = moment(val.buy_start_time).format('YYYY-MM-DD')
        }
      })
      if (params.content_arr.length > 0) {
        params.content_arr.forEach((val) => {
          val.discount = JSON.stringify(val.discount)
        })
      }
      let class_ids = []
      params.content_arr.forEach((item) => {
        if (item.project_type == 1 && item.class_id) {
          class_ids.push(item.class_id)
        }
      })
      if (class_ids.length > 0) {
        checkStudent({
          student_ids: [params.student_id],
          class_ids: class_ids,
        })
          .then((res) => {
            if (res.data.length > 0) {
              this.studentVisible = true
              this.conflict = res.data
            } else {
              console.log(11111)
              this.studentOk()
            }
          })
          .catch((err) => {
            this.$message.error(err.data.message || '冲突检测失败')
          })
      } else {
        console.log(11111)

        this.studentOk()
      }
    },
    // 确认报名弹窗
    sureApply() {
      if (!this.studentInfo) {
        this.$message.error('请选择学生')
        return
      }
      if (this.data.length == 0) {
        this.$message.error('请添加购买项目')
        return
      }
      let btnStyle = JSON.parse(JSON.stringify(this.btnStyle))
      let arr = []
      btnStyle.forEach((val) => {
        if (val.check && +Number(val.price) >= 0) {
          arr.push({
            charge_type: val.type,
            real_price: val.price,
          })
        }
      })
      if (arr.length == 0) {
        this.$message.error('请选择支付方式')
        return
      }
      let msg = []
      this.data.forEach((val) => {
        if (val.project_type == 1) {
          val.price.forEach((item, index) => {
            if (item.id == val.price_type && item.type == 2) {
              let buyDay = new Date(moment(val.buy_start_time).format('YYYY-MM-DD')).getTime() / 1000
              let nowDay = new Date(moment().format('YYYY-MM-DD')).getTime() / 1000
              if (nowDay > buyDay) {
                msg.push(val.name)
              }
            }
          })
        }
      })
      if (msg.length > 0) {
        let str = msg.join('、')
        let that = this
        this.$confirm({
          title: '提示',
          content:
            '您购买的“ ' + str + ' ”开始时间早于今天，报名完成后，系统将自动生成截止昨天的按天课消记录，确认报名吗？',
          okText: '确定',
          okType: 'danger',
          cancelText: '取消',
          onOk() {
            that.sureApplyVisible = true
          },
          onCancel() {
            console.log('Cancel')
          },
        })
      } else {
        this.sureApplyVisible = true
      }
    },
    showChild(e) {
      if (e == 'courseComponents') {
        this.$refs.course.showModal(this.courseSelectRows, this.form.structures_id)
      } else if (e == 'itemComponents') {
        this.$refs.item.showModal()
      } else if (e == 'cost') {
        this.$refs.cost.showModal()
      }
    },
    studentModelReturnData(e) {
      let params = JSON.parse(JSON.stringify(e))
      this.studentInfo = params
    },
    reloadStudent(data) {
      this.readingStudent_index = [data.id]
      this.studentInfo = data
    },
    // 选择课程后的参数获取
    courseData(data) {
      let e = JSON.parse(JSON.stringify(data))
      if (e.length > 0) {
        this.status = true
      }
      let choiceCourseArr = []
      e.forEach((val, index) => {
        let arr = []

        this.data.forEach((item) => {
          if (item.project_type == 1) {
            arr.push(item.id)
          }
        })
        choiceCourseArr.push(val.id)
        if (val.price.length > 0) {
          val.project_id = val.id
          val.project_type = 1 //类型：1课程，2物品，3费用
          val.course_type_num = val.type //一对一或一对多  1——>对一 2——>对多
          val.price.forEach((item) => {
            if (item.id) {
              if (item.type == 1) {
                if (item.number == 1) {
                  item.name = item.name + '(' + item.unit_price + '元/课时' + ')'
                } else {
                  item.name = item.name + '(' + item.total_price + '元' + item.number + '课时)'
                }
              } else {
                if (item.id && item.type == 2) {
                  if (item.number == 1) {
                    item.name = item.name + '(' + item.unit_price + '元/天' + ')'
                  } else {
                    item.name = item.name + '(' + item.total_price + '元' + item.number + '天)'
                  }
                }
              }
            }
          })
          val.price_type = val.price[0].id //当前选择的定价标准ID

          val.choice_combo = val.price[0] //当前选择的定价标准 对象
          val.unit_price = val.price[0].unit_price //当前单价
          val.class_id = undefined
          val.total_number = 1
          val.buy_number = val.price[0].number //购买数量
          val.give_number = 0 //赠送数量
          val.signing_price = val.price[0].unit_price //总价
          val.course_type = 0 //表明当前选择课程类型 课程类型：0购买，1新报，2续报，3扩科
          val.buy_start_time = moment()
          let start = new Date(moment(val.buy_start_time).format('YYYY-MM-DD'))
          let end = new Date(moment(val.buy_start_time).format('YYYY-MM-DD'))

          if (val.price[0].type == 2) {
            if (val.price[0].number >= 1) {
              end.setDate(start.getDate() + val.price[0].number)
              let endTime = new Date(end)
              val.buy_end_time =
                endTime.getFullYear() + '-' + (endTime.getMonth() + 1) + '-' + endTime.getDate() || null
            } else {
              end.setDate(start.getDate() + 1)
              val.buy_end_time =
                endTime.getFullYear() + '-' + (endTime.getMonth() + 1) + '-' + endTime.getDate() || null
            }
          }
          val.discount = {
            //优惠方式  type：1直减 2折扣
            type: 1,
            value: 0,
          }
          if (arr.indexOf(val.id) == -1) {
            this.data.push(val)
            this.changePriceType(val, index, 'add')
          }
        } else {
          val.project_id = val.id
          val.project_type = 1 //类型：1课程，2物品，3费用
          val.course_type_num = val.type //一对一或一对多  1——>一对一 2——>一对多
          val.price_type = null //当前选择的定价标准ID
          val.unit_price = null //当前单价
          val.class_id = undefined
          val.total_number = 1
          val.buy_number = 1 //购买数量
          val.give_number = 0 //赠送数量
          val.signing_price = 0 //总价
          val.course_type = 0 //表明当前选择课程类型 课程类型：0购买，1新报，2续报，3扩科
          val.buy_start_time = moment()
          let start = new Date(moment(val.buy_start_time).format('YYYY-MM-DD'))
          let end = new Date(moment(val.buy_start_time).format('YYYY-MM-DD'))
          end.setDate(start.getDate() + val.total_number)
          if (val.total_number > 0 && val.buy_start_time) {
            let endTime = new Date(end)
            val.buy_end_time = endTime.getFullYear() + '-' + (endTime.getMonth() + 1) + '-' + endTime.getDate() || null
          }
          val.discount = {
            //优惠方式  type：1直减 2折扣
            type: 1,
            value: 0,
          }
          if (arr.indexOf(val.id) == -1) {
            this.data.push(val)
          }
        }
      })
      e.forEach((item) => {
        this.itemData(item.goods)
        this.costData(item.costs)
      })
      this.courseSelectRows = choiceCourseArr
    },
    // 选择物品后的参数获取
    itemData(data) {
      data.forEach((val) => {
        val.project_id = val.id
        val.project_type = 2
        val.total_number = 1
        val.buy_number = 1 //购买数量
        val.give_number = 0 //赠送数量
        val.signing_price = val.unit_price //总价
        val.buy_start_time = null
        val.buy_end_time = null
        val.course_type = null
        val.discount = {
          //优惠方式  type：1直减 2折扣
          type: 1,
          value: 0,
        }
        let arr = []
        this.data.forEach((item) => {
          if (item.project_type && item.project_type == 2) {
            arr.push(item.id)
          }
        })
        if (arr.length > 0) {
          if (arr.indexOf(val.id) == -1) {
            this.data.push(val)
          }
        } else {
          this.data.push(val)
        }
      })
    },
    // 选择费用后的参数获取
    costData(params) {
      params.forEach((val) => {
        val.project_id = val.id
        val.project_type = 3
        val.total_number = 1
        val.buy_number = 1 //购买数量
        val.give_number = 0 //赠送数量
        val.signing_price = val.unit_price //总价
        val.buy_start_time = null
        val.buy_end_time = null
        val.course_type = null
        val.discount = {
          //优惠方式  type：1直减 2折扣
          type: 1,
          value: 0,
        }
        let arr = []
        this.data.forEach((item) => {
          if (item.project_type && item.project_type == 3) {
            arr.push(item.id)
          }
        })
        if (arr.length > 0) {
          if (arr.indexOf(val.id) == -1) {
            this.data.push(val)
          }
        } else {
          this.data.push(val)
        }
      })
    },
    //修改购买数量
    changeTotalNum(e, index, type) {
      if (type) {
        e.total_number = e.buy_number + e.give_number
        let benefit = e.discount.value
        if (e.discount.type == 1 && benefit >= 0) {
          //直减  计算总价
          if (benefit < Number(e.signing_price)) {
            e.signing_price = Number(e.unit_price) - Number(e.discount.value)
          } else {
            e.signing_price = 0
          }
        } else if (e.discount.type == 2 && benefit > 0) {
          if (e.buy_number) {
            e.signing_price = this.accMul(e.unit_price, (e.buy_number * e.discount.value) / 10)
          } else {
            e.signing_price = 0
          }
        } else if (e.discount.type == 2 && benefit == 0) {
          e.signing_price = e.unit_price
        }
      } else {
        if (!e.buy_number || e.buy_number < 1) {
          e.buy_number = 1
        }
        e.total_number = e.buy_number + e.give_number
        let benefit = e.discount.value
        if (e.buy_number > 0) {
          if (e.discount.type == 1 && benefit >= 0) {
            //直减  计算总价
            if (benefit < this.accMul(e.buy_number, e.unit_price)) {
              e.signing_price = this.accMul(e.buy_number, e.unit_price) - Number(e.discount.value)
            } else {
              e.signing_price = 0
            }
          } else if (e.discount.type == 2 && benefit > 0) {
            e.signing_price = this.accMul(this.accMul(e.buy_number, e.unit_price), e.discount.value / 10)
          } else if (e.discount.type == 2 && benefit == 0) {
            e.signing_price = this.accMul(e.buy_number, e.unit_price)
          }
        } else {
          e.signing_price = 0
        }
      }

      this.changeDate(e, index)
      this.data.splice(index, 1, e)
    },
    //乘法计算
    accMul(arg1, arg2) {
      let m = 0
      let s1 = arg1.toString()
      let s2 = arg2.toString()
      try {
        m += s1.split('.')[1].length
      } catch (e) { }
      try {
        m += s2.split('.')[1].length
      } catch (e) { }
      return (Number(s1.replace('.', '')) * Number(s2.replace('.', ''))) / Math.pow(10, m)
    },
    //切换开始时间
    changeDate(e, index) {
      let start = new Date(moment(e.buy_start_time).format('YYYY-MM-DD'))
      let end = new Date(moment(e.buy_start_time).format('YYYY-MM-DD'))
      if (e.total_number >= 1) {
        end.setDate(start.getDate() + e.total_number - 1)
        if (+Number(e.total_number) > 0 && e.buy_start_time) {
          let endTime = new Date(end)
          e.buy_end_time = endTime.getFullYear() + '-' + (endTime.getMonth() + 1) + '-' + endTime.getDate() || null
        }
        this.data.splice(index, 1, e)
      }
    },
    //优惠、直减
    changeDiscount(e, index, type) {
      console.log(e, type)

      if (type) {
        if (e.discount.value != 0) {
          e.discount.value = e.discount.value.replace(/^0+/, '')
        }
        if (e.discount.type == 1) {
          if (Number(e.discount.value) > Number(e.total_price)) {
            e.discount.value = e.total_price
            e.signing_price = 0
          } else if (Number(e.total_price) - Number(e.discount.value) >= 0) {
            e.signing_price = Number(e.total_price) - Number(e.discount.value)
          }
        }
        if (e.discount.type == 2) {
          //折扣计算总价
          if (e.discount.value > 0 && e.discount.value < 10) {
            e.signing_price = Number(this.accMul(Number(e.total_price), Number(e.discount.value) / 10))
            // console.log(Number(e.signing_price),Number(e.discount.value) / 10,Number(e.discount.value))
            // console.log(this.accMul(  Number(e.signing_price),  Number(e.discount.value) / 10),31)
          } else if (e.discount.value >= 10) {
            e.discount.value = 9
            // console.log(this.accMul(Number(e.signing_price), Number(e.discount.value / 10)),123)
            e.signing_price = Number(this.accMul(Number(e.total_price), Number(e.discount.value / 10)))
          }
        }
      } else {
        if (e.discount.value != 0) {
          e.discount.value = e.discount.value.replace(/^0+/, '')
        }
        if (e.discount.type == 1) {
          //直减计算总价
          if (e.discount.value > e.unit_price * e.buy_number) {
            e.discount.value = e.unit_price * e.buy_number
          }
          if (e.unit_price * e.buy_number - e.discount.value > 0) {
            e.signing_price = Number((e.buy_number * e.unit_price - e.discount.value).toFixed(2))
          } else {
            e.signing_price = 0
          }
        }
        if (e.discount.type == 2) {
          //折扣计算总价
          if (e.discount.value > 0 && e.discount.value < 10) {
            e.signing_price = Number((e.unit_price * e.buy_number * (e.discount.value / 10)).toFixed(2))
          } else if (e.discount.value >= 10) {
            e.discount.value = 9
            e.signing_price = Number((e.unit_price * e.buy_number * (e.discount.value / 10)).toFixed(2))
          }
        }
      }
      this.data.splice(index, 1, e)
    },
    //定价标准切换
    changePriceType(e, index, type) {
      e.price.forEach((val) => {
        if (val.id == e.price_type) {
          e.choice_combo = val
          if (val.type == 1) {
            e.buy_start_time = null
            e.buy_end_time = null
          } else {
            e.buy_start_time = moment()
          }
          if (val.number > 1) {
            e.buy_number = val.number
            e.total_number = val.number
            e.total_price = val.total_price
            e.signing_price = val.total_price
            e.unit_price = val.total_price
            e.discount.value = 0
            e.disable = true
            if (type !== 'add') {
              this.changeDate(e, index)
            }
          } else {
            e.discount.value = 0
            e.buy_number = 1 //购买数量
            e.total_number = 1
            e.signing_price = val.unit_price //总价
            e.unit_price = val.unit_price
            e.disable = false
          }
          e.give_number = 0 //赠送数量
          if (type !== 'add') {
            this.changeDate(e, index)
          }
        }
      })
    },
    //购买类型
    changeCourseType(e, index) {
      this.data.splice(index, 1, e)
    },
    //删除购买项目  删完后验证 购买内容是否包含课程(没有课程允许切换校区)
    delProject(record, index) {
      this.data.splice(index, 1)
      let type = false
      this.data.forEach((val) => {
        if (val.project_type == 1) {
          type = true
        }
      })
      this.status = type
    },
    //支付类型
    changePayWay(a, b, index) {
      // b==付款方式的Type
      // a.target.checked  选中状态
      if (a.target.checked == true) {
        let num = 0
        this.btnStyle.forEach((val) => {
          num = num + Number(val.price)
        })
        let noPay = (this.form.receivable - num).toFixed(2)
        this.btnStyle[index].check = a.target.checked
        this.btnStyle[index].price = noPay > 0 ? noPay : 0
      } else {
        this.btnStyle[index].check = a.target.checked
        this.btnStyle[index].price = 0
      }
    },

    moment,
  },
  watch: {
    data: {
      handler(val) {
        let num = 0
        val.forEach((item) => {
          num = num + Number(item.signing_price)
        })
        if (num > 0) {
          this.form.receivable = num.toFixed(2)
        } else {
          this.form.receivable = null
        }
      },
      deep: true,
    },
    btnStyle: {
      handler(val) {
        let num = 0
        val.forEach((item) => {
          if (item.check == true) {
            num = num + Number(item.price)
          }
        })
        this.form.real_price = num.toFixed(2)
      },
      deep: true,
    },
  },
}
</script>
<style lang="less" scoped>
.title {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;

  .title-left {
    font-weight: bold;
  }

  .title-right {
    color: rgb(255, 255, 255);
    font-size: 12px;
    padding: 4px 10px;
    background: rgb(255, 117, 25);
    border-radius: 3px;
  }
}

.datas {
  max-height: 150px;
  background: rgb(255, 255, 255);
  border-width: 1px;
  border-style: solid;
  border-color: rgb(232, 232, 232);
  border-image: initial;
  border-radius: 4px;
  padding: 16px;
  overflow: auto;
}

.payWays {
  width: 1000px;
  display: flex;
  flex-flow: wrap;

  .payWayBtn {
    padding: 0 8px;
    width: 260px;
    border: 1px solid #e8e8e8;
    margin: 0 10px 10px 0;
    border-radius: 4px;
    // height: 50px;
    // line-height:;
    align-items: center;
  }
}

.receivable {
  text-align: right;
  padding: 10px;
  padding-right: 24px;

  .receivable_num {
    color: #ff8534;
    font-size: 24px;
  }
}

.footer {
  position: fixed;
  bottom: 0;
  right: 0;
  width: 100%;
  text-align: right;
  z-index: 1;
}

.otherInfo {
  .title {
    padding-left: 2px;
    padding-bottom: 10px;
    font-size: 16px;
    border-bottom: 1px solid #e8e8e8;
  }

  .form_ {
    width: 800px;
    padding-top: 10px;
  }
}

.studentInfo {
  border: 1px solid #e8e8e8;
  border-radius: 4px;
  margin-top: 15px;
  padding: 5px 10px;

  .infoBySelf {
    .name {
      padding: 0 10px;
    }

    .edit {
      padding: 0 10px;
    }
  }
}

.applyInfomation {
  padding-top: 10px;
  border-top: 1px solid #e8e8e8;
}
</style>
<style lang="less">
.form_title {
  div {
    label {
      font-size: 16px !important;
    }
  }
}
</style>
